/**
 * 统一设置管理 Composable
 * 整合所有设置相关的状态管理和操作
 */

import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { 
  unifiedSettings, 
  validateUnifiedSettings, 
  mergeSettings,
  resetSettings,
  type UnifiedSettings,
  type SettingsCategory,
  SETTINGS_CATEGORIES
} from '@/config/unified-settings'

// 全局设置状态
const currentSettings = ref<UnifiedSettings>(cloneDeep(unifiedSettings))
const settingsLoading = ref(false)
const settingsChanged = ref(false)

// 配置验证状态
const configValidation = ref({ valid: true, errors: [] as string[] })

// 监听配置变化并重新验证
watch(currentSettings, (newSettings) => {
  const { valid, errors } = validateUnifiedSettings(newSettings)
  configValidation.value = { valid, errors }
  
  if (!valid) {
    errors.forEach(error => ElMessage.error(`配置错误: ${error}`))
  }
}, { deep: true, immediate: true })

/**
 * 统一设置管理 Composable
 */
export function useUnifiedSettings() {
  // 更新整个配置
  const updateSettings = (newSettings: Partial<UnifiedSettings>) => {
    currentSettings.value = mergeSettings(currentSettings.value, newSettings)
    settingsChanged.value = true
    ElMessage.success('设置已更新')
  }

  // 更新特定配置项
  const updateSetting = (path: string, value: unknown) => {
    const keys = path.split('.')
    let current: Record<string, unknown> = currentSettings.value as Record<string, unknown>
    
    for (let i = 0; i < keys.length - 1; i++) {
      if (!current[keys[i]]) {
        current[keys[i]] = {}
      }
      current = current[keys[i]] as Record<string, unknown>
    }
    
    current[keys[keys.length - 1]] = value
    settingsChanged.value = true
  }

  // 重置配置
  const resetSettingsToDefault = (category?: keyof UnifiedSettings) => {
    currentSettings.value = resetSettings(category)
    settingsChanged.value = false
    ElMessage.success('配置已重置为默认值')
  }

  // 验证配置
  const validateSettings = () => {
    const result = validateUnifiedSettings(currentSettings.value)
    configValidation.value = result
    return result
  }

  // 监听配置变化
  const watchSettings = (callback: (newSettings: UnifiedSettings, oldSettings: UnifiedSettings) => void) => {
    return watch(currentSettings, callback, { deep: true })
  }

  return {
    // 状态
    settings: currentSettings,
    loading: settingsLoading,
    changed: settingsChanged,
    validation: configValidation,
    
    // 方法
    updateSettings,
    updateSetting,
    resetSettingsToDefault,
    validateSettings,
    watchSettings
  }
}

/**
 * 主题设置专用 Composable
 */
export function useThemeSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const themeSettings = computed(() => settings.value.theme)
  
  const setThemeMode = (mode: 'light' | 'dark' | 'auto') => {
    updateSetting('theme.mode', mode)
  }
  
  const setPrimaryColor = (color: string) => {
    updateSetting('theme.primaryColor', color)
  }
  
  const setBorderRadius = (radius: 'none' | 'small' | 'medium' | 'large') => {
    updateSetting('theme.borderRadius', radius)
  }
  
  return {
    themeSettings,
    setThemeMode,
    setPrimaryColor,
    setBorderRadius
  }
}

/**
 * 界面设置专用 Composable
 */
export function useInterfaceSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const interfaceSettings = computed(() => settings.value.interface)
  
  const setSidebarCollapsed = (collapsed: boolean) => {
    updateSetting('interface.sidebarCollapsed', collapsed)
  }
  
  const setSidebarMode = (mode: 'vertical' | 'horizontal' | 'mix') => {
    updateSetting('interface.sidebarMode', mode)
  }
  
  const setPageSize = (size: number) => {
    updateSetting('interface.pageSize', size)
  }
  
  const setShowBreadcrumb = (show: boolean) => {
    updateSetting('interface.showBreadcrumb', show)
  }
  
  const setShowTabs = (show: boolean) => {
    updateSetting('interface.showTabs', show)
  }
  
  const setShowLogo = (show: boolean) => {
    updateSetting('interface.showLogo', show)
  }
  
  return {
    interfaceSettings,
    setSidebarCollapsed,
    setSidebarMode,
    setPageSize,
    setShowBreadcrumb,
    setShowTabs,
    setShowLogo
  }
}

/**
 * 语言设置专用 Composable
 */
export function useLanguageSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const languageSettings = computed(() => settings.value.language)
  
  const setLocale = (locale: string) => {
    updateSetting('language.locale', locale)
  }
  
  const setFallbackLocale = (locale: string) => {
    updateSetting('language.fallbackLocale', locale)
  }
  
  return {
    languageSettings,
    setLocale,
    setFallbackLocale
  }
}

/**
 * 通知设置专用 Composable
 */
export function useNotificationSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const notificationSettings = computed(() => settings.value.notification)
  
  const setEnableSound = (enabled: boolean) => {
    updateSetting('notification.enableSound', enabled)
  }
  
  const setEnableDesktop = (enabled: boolean) => {
    updateSetting('notification.enableDesktop', enabled)
  }
  
  const setSoundVolume = (volume: number) => {
    updateSetting('notification.soundVolume', volume)
  }
  
  const setNotificationType = (type: 'system' | 'security' | 'business' | 'marketing', enabled: boolean) => {
    updateSetting(`notification.notificationTypes.${type}`, enabled)
  }
  
  return {
    notificationSettings,
    setEnableSound,
    setEnableDesktop,
    setSoundVolume,
    setNotificationType
  }
}

/**
 * 安全设置专用 Composable
 */
export function useSecuritySettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const securitySettings = computed(() => settings.value.security)
  
  // 计算属性
  const passwordMinLength = computed(() => securitySettings.value.passwordMinLength)
  const passwordMaxLength = computed(() => securitySettings.value.passwordMaxLength)
  const sessionTimeout = computed(() => securitySettings.value.sessionTimeout)
  const maxLoginAttempts = computed(() => securitySettings.value.maxLoginAttempts)
  const twoFactorAuth = computed(() => securitySettings.value.twoFactorAuth)
  
  const setSessionTimeout = (timeout: number) => {
    updateSetting('security.sessionTimeout', timeout)
  }
  
  const setMaxLoginAttempts = (attempts: number) => {
    updateSetting('security.maxLoginAttempts', attempts)
  }
  
  const setPasswordLength = (minLength: number, maxLength: number) => {
    updateSetting('security.passwordMinLength', minLength)
    updateSetting('security.passwordMaxLength', maxLength)
  }
  
  const setTwoFactorAuth = (enabled: boolean) => {
    updateSetting('security.twoFactorAuth', enabled)
  }
  
  return {
    securitySettings,
    passwordMinLength,
    passwordMaxLength,
    sessionTimeout,
    maxLoginAttempts,
    twoFactorAuth,
    setSessionTimeout,
    setMaxLoginAttempts,
    setPasswordLength,
    setTwoFactorAuth
  }
}

/**
 * 验证码设置专用 Composable
 */
export function useCaptchaSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const captchaSettings = computed(() => settings.value.captcha)
  
  // 计算属性
  const isCaptchaEnabled = computed(() => captchaSettings.value.enabled)
  const captchaLength = computed(() => captchaSettings.value.length)
  const refreshOnError = computed(() => captchaSettings.value.refreshOnError)
  
  const setCaptchaEnabled = (enabled: boolean) => {
    updateSetting('captcha.enabled', enabled)
  }
  
  const setCaptchaLength = (length: number) => {
    updateSetting('captcha.length', length)
  }
  
  const setRefreshOnError = (refresh: boolean) => {
    updateSetting('captcha.refreshOnError', refresh)
  }
  
  return {
    captchaSettings,
    isCaptchaEnabled,
    captchaLength,
    refreshOnError,
    setCaptchaEnabled,
    setCaptchaLength,
    setRefreshOnError
  }
}

/**
 * 登录设置专用 Composable
 */
export function useLoginSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const loginSettings = computed(() => settings.value.login)
  
  // 计算属性
  const isRememberMeEnabled = computed(() => loginSettings.value.rememberMeEnabled)
  const autoLoginEnabled = computed(() => loginSettings.value.autoLoginEnabled)
  const maxLoginAttempts = computed(() => loginSettings.value.maxLoginAttempts)
  
  const setRememberMeEnabled = (enabled: boolean) => {
    updateSetting('login.rememberMeEnabled', enabled)
  }
  
  const setAutoLoginEnabled = (enabled: boolean) => {
    updateSetting('login.autoLoginEnabled', enabled)
  }
  
  const setMaxLoginAttempts = (attempts: number) => {
    updateSetting('login.maxLoginAttempts', attempts)
  }
  
  return {
    loginSettings,
    isRememberMeEnabled,
    autoLoginEnabled,
    maxLoginAttempts,
    setRememberMeEnabled,
    setAutoLoginEnabled,
    setMaxLoginAttempts
  }
}

/**
 * 系统设置专用 Composable
 */
export function useSystemSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const systemSettings = computed(() => settings.value.system)
  
  const setSystemName = (name: string) => {
    updateSetting('system.systemName', name)
  }
  
  const setSystemDescription = (description: string) => {
    updateSetting('system.systemDescription', description)
  }
  
  const setSystemLogo = (logo: string) => {
    updateSetting('system.systemLogo', logo)
  }
  
  const setEnableRegistration = (enabled: boolean) => {
    updateSetting('system.enableRegistration', enabled)
  }
  
  return {
    systemSettings,
    setSystemName,
    setSystemDescription,
    setSystemLogo,
    setEnableRegistration
  }
}

/**
 * 性能设置专用 Composable
 */
export function usePerformanceSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const performanceSettings = computed(() => settings.value.performance)
  
  const setEnableCache = (enabled: boolean) => {
    updateSetting('performance.enableCache', enabled)
  }
  
  const setCacheExpiry = (expiry: number) => {
    updateSetting('performance.cacheExpiry', expiry)
  }
  
  const setMaxConcurrentRequests = (max: number) => {
    updateSetting('performance.maxConcurrentRequests', max)
  }
  
  return {
    performanceSettings,
    setEnableCache,
    setCacheExpiry,
    setMaxConcurrentRequests
  }
}

/**
 * 数据设置专用 Composable
 */
export function useDataSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const dataSettings = computed(() => settings.value.data)
  
  const setDataRetention = (days: number) => {
    updateSetting('data.dataRetention', days)
  }
  
  const setBackupFrequency = (frequency: 'daily' | 'weekly' | 'monthly') => {
    updateSetting('data.backupFrequency', frequency)
  }
  
  const setEnableAutoBackup = (enabled: boolean) => {
    updateSetting('data.enableAutoBackup', enabled)
  }
  
  return {
    dataSettings,
    setDataRetention,
    setBackupFrequency,
    setEnableAutoBackup
  }
}

/**
 * 集成设置专用 Composable
 */
export function useIntegrationSettings() {
  const { settings, updateSetting } = useUnifiedSettings()
  
  const integrationSettings = computed(() => settings.value.integration)
  
  const setEnableApi = (enabled: boolean) => {
    updateSetting('integration.enableApi', enabled)
  }
  
  const setApiRateLimit = (limit: number) => {
    updateSetting('integration.apiRateLimit', limit)
  }
  
  const setEnableWebhook = (enabled: boolean) => {
    updateSetting('integration.enableWebhook', enabled)
  }
  
  const setWebhookUrl = (url: string) => {
    updateSetting('integration.webhookUrl', url)
  }
  
  return {
    integrationSettings,
    setEnableApi,
    setApiRateLimit,
    setEnableWebhook,
    setWebhookUrl
  }
}

/**
 * 设置分类管理 Composable
 */
export function useSettingsCategories() {
  const categories = computed(() => SETTINGS_CATEGORIES.filter(cat => cat.enabled))
  
  const getCategory = (key: keyof UnifiedSettings) => {
    return categories.value.find(cat => cat.key === key)
  }
  
  const getCategoryByOrder = (order: number) => {
    return categories.value.find(cat => cat.order === order)
  }
  
  return {
    categories,
    getCategory,
    getCategoryByOrder
  }
}

// 导出所有 Composable
export {
  type UnifiedSettings,
  type SettingsCategory,
  SETTINGS_CATEGORIES
}
